package mall.repository;

import mall.core.jdbc.Repository;
import mall.entity.Config;
import org.springframework.jdbc.core.BeanPropertyRowMapper;

import java.util.ArrayList;
import java.util.List;

public class ConfigRepository extends Repository {

    public List<Config> selectList() {
        return jdbcTemplate.query("select * from  config", new  BeanPropertyRowMapper<>(Config.class));
    }

    public List<Config> selectList(Config config) {
        StringBuilder sb = new StringBuilder("select * from  config where 1=1 ");
        List<Object> params = new ArrayList<>();

        if (config.getId() != null) {
            sb.append(" and id = ?");
            params.add(config.getId());
        }

        if (config.getKey() != null) {
            sb.append(" and `key` like ?");
            params.add("%" + config.getKey() + "%");
        }

        return jdbcTemplate.query(sb.toString(), new BeanPropertyRowMapper<>(Config.class), params.toArray());
    }


    public int insert(Config config) {
        String sql = "insert into config(key, value, description) values(?, ?, ?)";
        return jdbcTemplate.update(sql, config.getKey(), config.getValue(), config.getDescription());
    }

    public int update(Config config) {
        String sql = "update   config set key = ?, value = ?, description = ? where id = ?";
        return jdbcTemplate.update(sql, config.getKey(), config.getValue(), config.getDescription(), config.getId());
    }

    public int deleteById(int id) {
        String sql = "delete from   config where id = ?";
        return jdbcTemplate.update(sql, id);
    }


    public Config selectById(int id) {
        String sql = "select * from   config where id = ?";
        List<Config> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Config.class), id);
        return list.isEmpty() ? null : list.get(0);
    }


    public Config selectByKey(String key) {
        String sql = "select * from   config where `key` like ?";
        List<Config> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Config.class), key);
        return list.isEmpty() ? null : list.get(0);
    }
}
